package org.jeecg.modules.wlhy.invoice.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyConfigService;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hyproject.service.IHyProjectService;
import org.jeecg.modules.wlhy.hytaxsalesinvoice.service.IHyTaxSalesinvoiceService;
import org.jeecg.modules.wlhy.invoice.entity.HyInvoice;
import org.jeecg.modules.wlhy.invoice.service.IHyInvoiceService;
import org.jeecg.modules.wlhy.invoiceinfo.entity.HyInvoiceInfo;
import org.jeecg.modules.wlhy.invoiceinfo.service.IHyInvoiceInfoService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.CodeUtil;
import org.jeecg.modules.wlhy.utils.HyStatusCheckUtil;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: hy_invoice
 * @Author: jeecg-boot
 * @Date:   2020-12-21
 * @Version: V1.0
 */
@Api(tags="发票管理")
@RestController
@RequestMapping("/invoice/hyInvoice")
@Slf4j
public class HyInvoiceController extends JeecgController<HyInvoice, IHyInvoiceService> {

	 @Autowired
	 private IHyInvoiceService hyInvoiceService;

	 @Autowired
	 private IHyShippingNoteService hyShippingNoteService;

	 @Autowired
	 private IHySettingService settingService;

	 @Autowired
	 private IHyInvoiceInfoService hyInvoiceInfoService;

	 @Autowired
	 private UserUtil userUtil;

//	 @Autowired private IHyShippingNoteGasService hyShippingNoteGasService;

	 @Autowired
	 private IHyCompanyService hyCompanyService;

	 @Autowired
	 private IHyTaxSalesinvoiceService taxSalesinvoiceService;

	 @Resource
	 private IHyCompanyConfigService companyConfigService ;

	 @Autowired
	 private IHyCustomerService hyCustomerService;

	 @Autowired
	 private IHyProjectService hyProjectService;
	/**
	 * 分页列表查询
	 *
	 * @param hyInvoice
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="hy_invoice-分页列表查询", notes="hy_invoice-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HyInvoice hyInvoice,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		HyCustomer customer = userUtil.getCustomer();

		String invoiceHm = hyInvoice.getInvoiceHm();
		hyInvoice.setInvoiceHm(null);
		QueryWrapper<HyInvoice> queryWrapper = QueryGenerator.initQueryWrapper(hyInvoice, req.getParameterMap());
		if (StringUtils.isNotBlank(invoiceHm)) {
			queryWrapper.like("invoice_hm", invoiceHm.trim());
		}

		if (null != customer) {
			queryWrapper.eq("customer_id", customer.getId());
		}

		Page<HyInvoice> page = new Page<HyInvoice>(pageNo, pageSize);
		IPage<HyInvoice> pageList = hyInvoiceService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/customerReqList")
	 public Result<?> customerReqList(HyInvoice hyInvoice,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 HyCustomer customer = userUtil.getCustomer();
		 if (customer == null) {
			 return Result.error("货主信息不存在");
		 }

		 QueryWrapper<HyInvoice> queryWrapper = QueryGenerator.initQueryWrapper(hyInvoice, req.getParameterMap());
		 queryWrapper.eq("customer_id", customer.getId())
		 			 .eq("invoice_status","1");


		 Page<HyInvoice> page = new Page<HyInvoice>(pageNo, pageSize);
		 IPage<HyInvoice> pageList = hyInvoiceService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @GetMapping(value = "/customerCompalateList")
	 public Result<?> customerCompalateList(HyInvoice hyInvoice,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		 HyCustomer customer = userUtil.getCustomer();
		 if (customer == null) {
			 return Result.error("货主信息不存在");
		 }
		 String invoiceHm = hyInvoice.getInvoiceHm();
		 hyInvoice.setInvoiceHm(null);
		 QueryWrapper<HyInvoice> queryWrapper = QueryGenerator.initQueryWrapper(hyInvoice, req.getParameterMap());
		 queryWrapper.eq("customer_id",customer.getId())
				 .eq("invoice_status","2");
		 if(StringUtils.isNotBlank(invoiceHm)){
			 queryWrapper.like("invoice_hm",invoiceHm.trim());
		 }


		 Page<HyInvoice> page = new Page<HyInvoice>(pageNo, pageSize);
		 IPage<HyInvoice> pageList = hyInvoiceService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @PostMapping(value = "/getInvoiceCustomerInfo")
	 public Result<?> getInvoiceCustomerInfo(@RequestBody HyInvoice hyInvoice) {

		 String ids = hyInvoice.getShippingIds();
		 if (StringUtils.isEmpty(ids)) {
			 return Result.error("运单数不能为空！");
		 }

		 List<HyShippingNote> shippingNotes = hyShippingNoteService.listByIds(Arrays.asList(ids.split(",")));
		 if(hyInvoice.getShippingNums() != shippingNotes.size()){
			 return Result.error("运单数错误!");
		 }
		 HyCustomer customer = null;
		 if(userUtil.isSys()){
			 String tcustomerId = "";
			 for (HyShippingNote hyShippingNote : shippingNotes) {
				 String customerId = hyShippingNote.getCustomerId();
				 if(StringUtils.isEmpty(tcustomerId)){
					 tcustomerId = customerId;
				 }else {
					 if(!StringUtils.equals(tcustomerId,customerId)){
						 return Result.error("运单所属货主不一致!");
					 }
				 }
			 }
			 customer = hyCustomerService.getById(tcustomerId);
		 }else {
			 customer = userUtil.getCustomer();
		 }

		 if(customer==null){
			 return Result.error("货主信息不存在!");
		 }
		 HyInvoiceInfo invoiceInfo = hyInvoiceInfoService.getByOwnerId(customer.getId());
		 if(invoiceInfo==null){
			 return Result.error("尚未填写开票信息，请到“开票管理-开票信息设置”中填写后再申请开票！");
		 }

		 String invoiceWeightType = hyInvoice.getInvoiceWeightType();
		 if(!"1".equals(invoiceWeightType) && !"2".equals(invoiceWeightType)  && !"0".equals(invoiceWeightType)){
			 throw new JeecgBootException("开票数量选择错误!");
		 }


		 List<Map> data = this.getInvoiceInfo(hyInvoice,customer,invoiceInfo,shippingNotes);
		 List<HyInvoice> invoiceInfos = new ArrayList<>();
		 for (Map map : data) {
			 HyInvoice invoice = (HyInvoice) map.get("invoice");
			 invoiceInfos.add(invoice);
		 }
		 return Result.OK(invoiceInfos);
	 }

	 private List<Map> getInvoiceInfo(HyInvoice hyInvoice , HyCustomer customer,HyInvoiceInfo customerInvoiceInfo,List<HyShippingNote> hyShippingNotes){
		 //开票数量选择(1装货量2卸货量)
		 String invoiceWeightType = hyInvoice.getInvoiceWeightType();
		 if(!"1".equals(invoiceWeightType) && !"2".equals(invoiceWeightType)  && !"0".equals(invoiceWeightType)){
			 throw new JeecgBootException("开票数量选择错误!");
		 }
		 String tcompanyId = "";
		 for (HyShippingNote hyShippingNote : hyShippingNotes) {
			 if(!StringUtils.equals(hyShippingNote.getCustomerId(),customer.getId())){
				 throw new JeecgBootException("运单所属货主信息错误!");
			 }
			 String companyId = hyShippingNote.getCompanyId();
			 if(StringUtils.isEmpty(companyId)){
				 throw new JeecgBootException("运单所属公司信息错误!");
			 }
			 if(StringUtils.isEmpty(tcompanyId)){
				 tcompanyId = companyId;
			 }else {
				 if(!StringUtils.equals(tcompanyId,companyId)){
					 throw new JeecgBootException("运单所属公司不一致!");
				 }
			 }

			 String orderMode = hyShippingNote.getOrderMode();
			 HyStatusCheckUtil.checkOrderMode(orderMode);
//			 String payChannel = hyShippingNote.getPayChannel();
//			 if(!"1".equals(payChannel)){
//				 throw new JeecgBootException("运费支付渠道错误!");
//			 }

			 //发票接口默认取支付完成的运单，如果invoicedFlag=1时表示开启了先票后款。
			 String invoicedFlag = this.settingService.getSettingValueByTag("invoiced_before_payment");
			 if ("1".equals(invoicedFlag)) {
				 if (!"4".equals(hyShippingNote.getShippingPayStatus())
				  && !"5".equals(hyShippingNote.getShippingPayStatus())
				  && !"6".equals(hyShippingNote.getShippingPayStatus())) {
					 throw new JeecgBootException("所选运单未对账完成,不能开票!");
				 }
			 } else {
				 if (!"6".equals(hyShippingNote.getShippingPayStatus())) {
					 throw new JeecgBootException("所选运单未支付完成,不能开票!");
				 }
			 }

			 if(!"0".equals(hyShippingNote.getBillStatus())){
				 throw new JeecgBootException("所选运单已开票,不能重复开票!");
			 }
//			 if(payType == null){
//				 payType = hyShippingNote.getPayType();
//			 }else {
//				 if(!StringUtils.equals(payType,hyShippingNote.getPayType())){
//					 throw new JeecgBootException("运单结算方式不统一,不能开票!");
//				 }
//			 }
		 }

		 //分公司开票信息
		 HyCompany company = hyCompanyService.getById(tcompanyId);
		 if(company == null){
			 throw new JeecgBootException("分公司信息不存在！");
		 }
		 BigDecimal invoiceEd = company.getInvoiceEd();
		 if(invoiceEd == null){
			 throw new JeecgBootException("分公司开票额度信息错误,请联系平台管理人员在“分公司管理”中填写后再申请开票！");
		 }
		 BigDecimal invoiceRate = company.getInvoiceRate();
		 String invoicePhone = company.getInvoicePhone();
		 String invoiceBank = company.getInvoiceBank();
		 String invoiceBankAccount = company.getInvoiceBankAccount();
		 if(StringUtils.isEmpty(invoicePhone)
			 ||StringUtils.isEmpty(invoiceBank)
			 ||StringUtils.isEmpty(invoiceBankAccount)
			 ||invoiceEd == null
			 ||invoiceRate == null
		 ){
			 throw new JeecgBootException("分公司开票信息未填写,请联系平台管理人员在“分公司管理”中填写后再申请开票！");
		 }


		 //单个发票不能超过10万额度,超过10W生成多张
		 BigDecimal tcostPayTotals = BigDecimal.ZERO;
		 List<HyShippingNote> items = new ArrayList<>();
		 List<List<HyShippingNote>>  wp = new ArrayList<>();
		 for (HyShippingNote hyShippingNote : hyShippingNotes) {
			 //计算合计
			 BigDecimal tt = BigDecimal.ZERO;
			 String orderMode = hyShippingNote.getOrderMode();
			 if("1".equals(orderMode)){
			 	tt = hyShippingNote.getCustomerFee();
			 }else if("3".equals(orderMode)){
				 tt = hyShippingNote.getAgentFee();
			 }else if("4".equals(orderMode)){
				 tt = hyShippingNote.getCustomerFee();
			 }
			 BigDecimal t = tcostPayTotals.add(tt);
			 //大于开票额度上限
			 if(t.compareTo(invoiceEd)  > -1){
				 wp.add(items);
				 items = new ArrayList<>();
				 items.add(hyShippingNote);
				 tcostPayTotals = tt;
			 }else {
				 tcostPayTotals = t;
				 items.add(hyShippingNote);
			 }
		 }
		 wp.add(items);
		 List<Map> rets = new ArrayList<>();
		 for (List<HyShippingNote> shippingNoteList : wp) {
		 	 Map ret = new HashMap();
			 HyInvoice invoiceItemInfo = this.getInvoiceItemInfo(hyInvoice, shippingNoteList, customerInvoiceInfo, company,invoiceWeightType);
			 ret.put("invoice" , invoiceItemInfo);
			 ret.put("list",shippingNoteList);
			 rets.add(ret);
		 }
		return rets;
	 }
	 private HyInvoice getInvoiceItemInfo(HyInvoice invoice , List<HyShippingNote> hyShippingNotes, HyInvoiceInfo customerInvoiceInfo,
										  HyCompany company,String invoiceWeightType ){
		 HyInvoice hyInvoice = new HyInvoice();
		 hyInvoice.setShippingNums(hyShippingNotes.size());
		 hyInvoice.setRemark(invoice.getRemark());
		 BigDecimal tgoodsWeightLoadings = BigDecimal.ZERO;
		 BigDecimal tgoodsWeightUnloadings = BigDecimal.ZERO;
		 BigDecimal tgoodsWeightMinis = BigDecimal.ZERO;
		 BigDecimal tgoodsWeightLosss = BigDecimal.ZERO;
		 BigDecimal tcostPayShippings = BigDecimal.ZERO;
		 BigDecimal tcostLosss = BigDecimal.ZERO;
		 BigDecimal tcostPayTotals = BigDecimal.ZERO;
		 BigDecimal tcostServices = BigDecimal.ZERO;
		 BigDecimal tgasAmount = BigDecimal.ZERO;
//		 BigDecimal tpreFees = BigDecimal.ZERO;

		 List<String> ids = new ArrayList<>();
		 for (HyShippingNote hyShippingNote : hyShippingNotes) {
			 //计算合计
			 tgoodsWeightLoadings = tgoodsWeightLoadings.add(hyShippingNote.getGoodsWeightLoading());
			 tgoodsWeightUnloadings =tgoodsWeightUnloadings.add(hyShippingNote.getGoodsWeightUnloading());
			 if (ObjectUtil.isNotEmpty(hyShippingNote.getGoodsWeightLoss())) {
				 tgoodsWeightLosss = tgoodsWeightLosss.add(hyShippingNote.getGoodsWeightLoss());
			 }

			 if(hyShippingNote.getGoodsWeightLoading().compareTo(hyShippingNote.getGoodsWeightUnloading())>0){
				 tgoodsWeightMinis = tgoodsWeightMinis.add(hyShippingNote.getGoodsWeightUnloading());
			 }else{
				 tgoodsWeightMinis = tgoodsWeightMinis.add(hyShippingNote.getGoodsWeightLoading());
			 }

			 if (ObjectUtil.isNotEmpty(hyShippingNote.getCostLoss())) {
				 tcostLosss = tcostLosss.add(hyShippingNote.getCostLoss());
			 }

			 String orderMode = hyShippingNote.getOrderMode();
			 if("1".equals(orderMode)){
				 BigDecimal driverFee = hyShippingNote.getDriverFee();
				 tcostPayShippings = tcostPayShippings.add(driverFee);
				 if("0".equals(hyShippingNote.getIzServiceOpenInvoicing())){
					 //服务费不开票
					 tcostPayTotals = tcostPayTotals.add(driverFee);
				 }else {
					 tcostPayTotals = tcostPayTotals.add(hyShippingNote.getCustomerFee());
				 }
			 }else if("3".equals(orderMode)){
				 BigDecimal agentFee = hyShippingNote.getAgentFee();
				 tcostPayShippings = tcostPayShippings.add(agentFee);
				 tcostPayTotals = tcostPayTotals.add(agentFee);
//				 if("0".equals(hyShippingNote.getIzServiceOpenInvoicing())){
//					 //服务费不开票
//					 tcostPayTotals = tcostPayTotals.add(agentFee);
//				 }else {
//					 tcostPayTotals = tcostPayTotals.add(hyShippingNote.getAgentCostPayTotal());
//				 }
			 }else if("4".equals(orderMode)){
				 BigDecimal driverFee = hyShippingNote.getDriverFee();
				 tcostPayShippings = tcostPayShippings.add(driverFee);
				 if("0".equals(hyShippingNote.getIzServiceOpenInvoicing())){
					 //服务费不开票
					 tcostPayTotals = tcostPayTotals.add(driverFee);
				 }else {
					 tcostPayTotals = tcostPayTotals.add(hyShippingNote.getCustomerFee());
				 }
			 }

			 tcostServices = tcostServices.add(hyShippingNote.getCostService());
			 if(!"0".equals(hyShippingNote.getIzUsedGas())) {
				 tgasAmount = tgasAmount.add(hyShippingNote.getGasRechargeAmount());
			 }

			 ids.add(hyShippingNote.getId());
		 }
		 String strids = String.join(",", ids.stream().map(String::valueOf).collect(Collectors.toList()));
		 hyInvoice.setShippingIds(strids);
		 tgoodsWeightLoadings = tgoodsWeightLoadings.setScale(2, BigDecimal.ROUND_HALF_UP);
		 tgoodsWeightUnloadings =tgoodsWeightUnloadings.setScale(2, BigDecimal.ROUND_HALF_UP);
		 tgoodsWeightMinis =tgoodsWeightMinis.setScale(2, BigDecimal.ROUND_HALF_UP);
		 tgoodsWeightLosss = tgoodsWeightLosss.setScale(2, BigDecimal.ROUND_HALF_UP);
		 tcostPayShippings = tcostPayShippings.setScale(2, BigDecimal.ROUND_HALF_UP);
		 tcostLosss = tcostLosss.setScale(2, BigDecimal.ROUND_HALF_UP);
		 tcostServices = tcostServices.setScale(2, BigDecimal.ROUND_HALF_UP);
		 tgasAmount = tgasAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
		 tcostPayTotals = tcostPayTotals.setScale(2, BigDecimal.ROUND_HALF_UP);

		 hyInvoice.setGoodsWeightLoading(tgoodsWeightLoadings);
		 hyInvoice.setGoodsWeightUnloading(tgoodsWeightUnloadings);
		 hyInvoice.setGoodsWeightLoss(tgoodsWeightLosss);
		 hyInvoice.setCostPayShipping(tcostPayShippings);
		 hyInvoice.setCostLoss(tcostLosss);
		 hyInvoice.setCostService(tcostServices);
		 hyInvoice.setGasAmount(tgasAmount);
		 hyInvoice.setCostPayTotal(tcostPayTotals);

		 //1装货量2卸货量
		 BigDecimal invoiceGoodsWeight = null;
		 if("2".equals(invoiceWeightType)){
			 invoiceGoodsWeight = tgoodsWeightUnloadings;
		 }else if("1".equals(invoiceWeightType)){
			 invoiceGoodsWeight = tgoodsWeightLoadings;
		 }else if("0".equals(invoiceWeightType)){
			 invoiceGoodsWeight = tgoodsWeightMinis;
		 }else {
			 throw new JeecgBootException("开票数量选择错误!");
		 }
		 hyInvoice.setInvoiceGoodsWeight(invoiceGoodsWeight);
		 //金额 = 价税合计/1.09
		 BigDecimal _invoiceRate = company.getInvoiceRate();
		 BigDecimal amt =  tcostPayTotals.divide(_invoiceRate.add(BigDecimal.ONE) , 9, BigDecimal.ROUND_HALF_UP);//.setScale(2, BigDecimal.ROUND_HALF_UP);
		 hyInvoice.setInvoiceAmt(amt);
		 //单价 = 金额 / 数量
		 BigDecimal price = amt.divide(invoiceGoodsWeight,9, BigDecimal.ROUND_HALF_UP);//.setScale(9, BigDecimal.ROUND_HALF_UP);;
		 hyInvoice.setInvoicePrice(price);
		 hyInvoice.setInvoiceRate(_invoiceRate);//税率
		 //税额 = 价税合计 - 金额
		 BigDecimal tax = tcostPayTotals.subtract(amt);
		 hyInvoice.setInvoiceTax(tax);
		 hyInvoice.setInvoiceTaxAmt(tcostPayTotals);//价税合计

		 //货主信息
		 if(customerInvoiceInfo == null){
			 throw new JeecgBootException("尚未填写开票信息，请到“开票管理-开票信息设置”中填写后再申请开票！");
		 }else{
			 hyInvoice.setCustomerId(customerInvoiceInfo.getOwnerId());
			 hyInvoice.setCustomerName(customerInvoiceInfo.getTaxpayerName());
			 hyInvoice.setCustomerCreditCode(customerInvoiceInfo.getTaxpayerCreditCode());
			 hyInvoice.setCustomerAddressPhone(customerInvoiceInfo.getAddress() + " " + customerInvoiceInfo.getPhone());
			 hyInvoice.setCustomerBank(customerInvoiceInfo.getDepositBank() + " " + customerInvoiceInfo.getBankAccount());
		 }
		 //分公司信息
		 hyInvoice.setCompanyId(company.getId());
		 hyInvoice.setCompanyName(company.getCompanyName());
		 hyInvoice.setCompanyCreditCode(company.getCreditCode());
		 hyInvoice.setCompanyAddressPhone(company.getScjydz() + " " + company.getInvoicePhone());
		 hyInvoice.setCompanyBank(company.getInvoiceBank() + " " + company.getInvoiceBankAccount());
		 return hyInvoice;
	 }

	@AutoLog(value = "hy_invoice-添加")
	@ApiOperation(value="hy_invoice-添加", notes="hy_invoice-添加")
	@PostMapping(value = "/add")
	@Transactional
	public Result<?> add(@RequestBody HyInvoice hyInvoices) {

		String ids = hyInvoices.getShippingIds();
		if (StringUtils.isEmpty(ids)) {
			return Result.error("运单数不能为空！");
		}

		List<HyShippingNote> shippingNotes = hyShippingNoteService.listByIds(Arrays.asList(ids.split(",")));
		if(hyInvoices.getShippingNums() != shippingNotes.size()){
			return Result.error("运单数错误!");
		}
		HyCustomer customer = null;
		if(userUtil.isSys()){
			String tcustomerId = "";
			for (HyShippingNote hyShippingNote : shippingNotes) {
				String customerId = hyShippingNote.getCustomerId();
				if(StringUtils.isEmpty(tcustomerId)){
					tcustomerId = customerId;
				}else {
					if(!StringUtils.equals(tcustomerId,customerId)){
						return Result.error("运单所属货主不一致!");
					}
				}
			}
			customer = hyCustomerService.getById(tcustomerId);
		}else {
			customer = userUtil.getCustomer();
		}

		if(customer==null){
			return Result.error("货主信息不存在!");
		}
		HyInvoiceInfo invoiceInfo = hyInvoiceInfoService.getByOwnerId(customer.getId());
		if(invoiceInfo==null){
			return Result.error("尚未填写开票信息，请到“开票管理-开票信息设置”中填写后再申请开票！");
		}

		String invoiceWeightType = hyInvoices.getInvoiceWeightType();
		if(!"1".equals(invoiceWeightType) && !"2".equals(invoiceWeightType) && !"0".equals(invoiceWeightType)){
			throw new JeecgBootException("开票数量选择错误!");
		}
		List<Map> data = this.getInvoiceInfo(hyInvoices,customer,invoiceInfo,shippingNotes);
		for (Map map : data) {
			HyInvoice invoice = (HyInvoice) map.get("invoice");
			List<HyShippingNote> hyShippingNotes = (List<HyShippingNote>) map.get("list");
			invoice.setInvoiceType(hyInvoices.getInvoiceType());
			invoice.setInvoiceStatus("1");//申请开票
			invoice.setRegDt(new Date());//申请开票时间
			invoice.setInvoiceNum(CodeUtil.getInvoiceNum());
			invoice.setInvoiceWeightType(invoiceWeightType);
			if (hyInvoiceService.save(invoice)) {
				String id = invoice.getId();
				for (HyShippingNote hyShippingNote : hyShippingNotes) {
					hyShippingNote.setBillStatus("2");
					hyShippingNote.setBillDtRequest(new Date());//申请开票时间
					hyShippingNote.setInvoiceId(id);
				}
				this.hyShippingNoteService.updateBatchById(hyShippingNotes);
			}else {
				return Result.error("操作失败！");
			}
		}
		return Result.OK("开票成功！");
	}

	/**
	 *  编辑
	 *
	 * @param hyInvoice
	 * @return
	 */
	@AutoLog(value = "hy_invoice-编辑")
	@ApiOperation(value="hy_invoice-编辑", notes="hy_invoice-编辑")
	@PutMapping(value = "/edit")
	@Transactional
	public Result<?> edit(@RequestBody HyInvoice hyInvoice) {
		HyInvoice old = hyInvoiceService.getById(hyInvoice.getId());
		if(old == null){
			return Result.error("记录不存在!");
		}
		if(!StringUtils.equals(old.getImg() , hyInvoice.getImg())){
			String ids = hyInvoice.getShippingIds();
			List<HyShippingNote> hyShippingNotes = hyShippingNoteService.listByIds(Arrays.asList(ids.split(",")));
			for (HyShippingNote hyShippingNote : hyShippingNotes) {
				hyShippingNote.setInvoiceImg(hyInvoice.getImg());
			}
			this.hyShippingNoteService.updateBatchById(hyShippingNotes);
		}
		hyInvoiceService.updateById(hyInvoice);
		return Result.OK("编辑成功!");
	}

	 @AutoLog(value = "hy_invoice-开票")
	 @ApiOperation(value="hy_invoice-开票", notes="hy_invoice-开票")
	 @PutMapping(value = "/kp")
	 @Transactional
	 public Result<?> kp(@RequestBody HyInvoice hyInvoice) {
		 HyInvoice invoice = hyInvoiceService.getById(hyInvoice.getId());
		 if(invoice == null){
			 return Result.error("记录不存在!");
		 }
		 String invoiceStatus = invoice.getInvoiceStatus();
		 if(!"1".equals(invoiceStatus)){
			 return Result.error("该记录已开票，不能重复开!");
		 }
		 String invoiceCode = hyInvoice.getInvoiceCode();
		 String img = hyInvoice.getImg();
		 String invoiceHm = hyInvoice.getInvoiceHm();
		 if(StringUtils.isEmpty(invoiceCode)){
			 return Result.error("发票代码不能为空!");
		 }
		 if(StringUtils.isEmpty(img)){
			 return Result.error("发票图片不能为空!");
		 }
		 if(StringUtils.isEmpty(invoiceHm)){
			 return Result.error("发票号码不能为空!");
		 }

		 invoice.setInvoiceCode(invoiceCode);
		 invoice.setInvoiceHm(invoiceHm);
		 invoice.setImg(img);
		 invoice.setInvoiceStatus("2");//已开票
		 invoice.setInvoiceDt(new Date());//开票时间
		 LoginUser loginUser = UserUtil.getLoginUser();
		 invoice.setKprName(loginUser.getRName());
		 invoice.setKprId(loginUser.getId());

		 String ids = invoice.getShippingIds();
		 List<HyShippingNote> hyShippingNotes = hyShippingNoteService.listByIds(Arrays.asList(ids.split(",")));
		 for (HyShippingNote hyShippingNote : hyShippingNotes) {
			 hyShippingNote.setInvoiceImg(img);
			 hyShippingNote.setBillStatus("3");
			 hyShippingNote.setBillDtComplate(new Date());
		 }
		 this.hyShippingNoteService.updateBatchById(hyShippingNotes);
		 hyInvoiceService.updateById(invoice);
		 //公司已开通天津税务，同步货主开票信息
		 QueryWrapper queryWrapper = new QueryWrapper();
		 queryWrapper.eq("tax_upload_type",1);
		 queryWrapper.eq("company_id",invoice.getCompanyId());
		 HyCompanyConfig hyCompanyConfig = companyConfigService.getOne(queryWrapper);

		 if(hyCompanyConfig != null && StringUtils.equals("1",hyCompanyConfig.getTjTaxUploadStatus())){
			 taxSalesinvoiceService.saveTaxSalesinvoice(invoice);
		 }
		 return Result.OK("开票成功!");
	 }

	 @AutoLog(value = "开票-撤销")
	 @ApiOperation(value="开票-撤销", notes="开票-撤销")
	 @PutMapping(value = "/chexiao")
	 @Transactional
	 public Result<?> chexiao(@RequestParam(name="id",required=true) String id) {
		 HyInvoice invoice = hyInvoiceService.getById(id);
		 if(invoice == null){
			 return Result.error("数据不存在!");
		 }
		 if(!"1".equals(invoice.getInvoiceStatus())){
			 return Result.error("不能撤销!");
		 }
		 HyCustomer customer = null;
		 if(!userUtil.isSys()){
			 customer = userUtil.getCustomer();
			 if(!StringUtils.equals(customer.getId(),invoice.getCustomerId())){
				 return Result.error("数据错误!");
			 }
		 }
		 List<HyShippingNote> hyShippingNotes =  hyShippingNoteService.getListByInvoiceId(id);
		 for (HyShippingNote hyShippingNote : hyShippingNotes) {
			 hyShippingNote.setBillStatus("0");//设置为待开票
			 hyShippingNote.setBillDtRequest(null);
			 hyShippingNote.setInvoiceId("");
		 }

		 hyInvoiceService.removeById(id);
		 hyShippingNoteService.updateBatchById(hyShippingNotes);
		 return Result.OK("操作成功");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "hy_invoice-通过id删除")
	@ApiOperation(value="hy_invoice-通过id删除", notes="hy_invoice-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		hyInvoiceService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "hy_invoice-批量删除")
	@ApiOperation(value="hy_invoice-批量删除", notes="hy_invoice-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hyInvoiceService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="hy_invoice-通过id查询", notes="hy_invoice-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HyInvoice hyInvoice = hyInvoiceService.getById(id);
		if(hyInvoice==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hyInvoice);
	}
	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="hy_invoice-通过id查询", notes="hy_invoice-通过id查询")
	 @GetMapping(value = "/queryById2")
	 public Result<?> queryById2(@RequestParam(name="id",required=true) String id) {
		 HyInvoice invoice = hyInvoiceService.getOne(new QueryWrapper<HyInvoice>()
		 .like("shipping_ids",id)
		 );
//		 HyInvoice hyInvoice = hyInvoiceService.getById(id);
		 if(invoice==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(invoice);
	 }


    /**
    * 导出excel
    *  @param request
    * @param hyInvoice
	 */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HyInvoice hyInvoice) {
    	if(!userUtil.isSys()){
			HyCustomer customer = userUtil.getCustomer();
			hyInvoice.setCustomerId(customer.getId());
		}
		return super.exportXls(request, hyInvoice, HyInvoice.class, "开票");
    }


	 /**
	  * 获取对象ID
	  *
	  * @return
	  */
	 private String getId(HyInvoice item) {
		 try {
			 return PropertyUtils.getProperty(item, "id").toString();
		 } catch (Exception e) {
			 e.printStackTrace();
			 return null;
		 }
	 }




    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HyInvoice.class);
    }

}
